package ut;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 * A class for logging.
 *
 * @author Thibault Langlois
 *
 */
public class Log {

    private static BufferedWriter logBW = null;
    private static String logfile;

    /**
     * Initializes the log file.
     */
    public static void setLogFile() {
        if (OsUtils.isLinux()) {
            setLogFile("/tmp/DCOdoc.log");
        } else if (OsUtils.isWindows()) {
            System.err.println("Where is the /tmp/ on windows ?");
            System.exit(1);
        }
    }

    public static void setLogFile(String filename) {
        logfile = filename;
        try {
            if (logBW != null) {
                logBW.close();
            }
            logBW = new BufferedWriter(new FileWriter(logfile, true));
        } catch (IOException e) {
            System.err.println("Cannot open log file " + logfile);
            e.printStackTrace();
        }
    }

    /**
     * Prints a message to the log.
     *
     * @param s
     */
    public static void prt(String s) {
        Date date = new Date();
        try {
            logBW.write(date + " | " + s + "\n");
            logBW.flush();
        } catch (IOException e) {
            System.err.println("Problem writing to log file.");
            e.printStackTrace();
        }
    }

    /**
     * Prints an error message to the log and exits.
     *
     * @param s
     */
    public static void err(String s) {
        Date date = new Date();
        try {
            logBW.write(date + " | ERROR " + s + "\n");
            System.err.println(s);
            logBW.flush();
        } catch (IOException e) {
            System.err.println("Problem writing to log file.");
            e.printStackTrace();
        }
        try {
            logBW.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.exit(666);
    }
}
